package cn.wolfcode.trip.app.web.controller;


import cn.wolfcode.trip.base.domain.Answer;
import cn.wolfcode.trip.base.domain.Question;
import cn.wolfcode.trip.base.query.QuestionQueryObject;
import cn.wolfcode.trip.base.service.IAnswerService;
import cn.wolfcode.trip.base.service.IQuestionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController@RequestMapping("/questions")
public class QuestionController {

    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IAnswerService answerService;

    @GetMapping("")
    public Object list(QuestionQueryObject qo){
        return questionService.selectQuestions(qo);
    }

    @GetMapping("/answers")
    public Object selectAnswerByQuestionId(Long id) {
        return answerService.selectAnswerByQuestionId(id);
    }

    @GetMapping("/{id}")
    public Object selectById(@PathVariable Long id){
        return questionService.selectById(id);
    }

    @PostMapping("")
    public Object saveAnswer(Answer answer){
        JSONResult json = new JSONResult();
        try {
            answerService.save(answer);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    @PutMapping("")
    public Object changeState(Long id,Long questionId){
        JSONResult json = new JSONResult();
        try {
            answerService.changeState(id);
            questionService.changeState(questionId);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    @PostMapping("/question")
    public Object saveQuestion(Question question){
        JSONResult json = new JSONResult();
        try {
            questionService.saveQuestion(question);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    @GetMapping("/viewCount")
    public Object updateViewCount(Long id){
        questionService.updateViewCount(id);
        return null;
    }
}
